package com.dtwenty.gaming.server;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.dtwenty.gaming.client.DataBase;
import com.dtwenty.gaming.client.LoginInfo;
import com.dtwenty.gaming.data.PlayerCharacter;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;


@SuppressWarnings("serial")
public class DataBaseImpl extends RemoteServiceServlet implements DataBase {
	
	private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("transactions-optional");
	
	public DataBaseImpl() {
//		System.out.println("creating DataBaseImpl");
	}
	
	public String saveData (PlayerCharacter character) {
		System.out.println("I've got a save request");
		EntityManager em = emf.createEntityManager();
		try {
			em.persist(character);
		} catch (Exception e) {
			System.out.println(e.toString());
			return "3. " + e.getMessage();
		} finally {
			em.close();
		}
		
		return "save successful";
	}
	
	public List<PlayerCharacter> getCharacters(LoginInfo li) {
		List<PlayerCharacter> ret = new ArrayList<PlayerCharacter>();
		EntityManager em = emf.createEntityManager();
		Query q = em.createQuery("SELECT p FROM PlayerCharacter p where p.playerName = :playerName");
		q.setParameter("playerName", li.getEmailAddress());
		for(Object pc : q.getResultList()){
			ret.add((PlayerCharacter)pc);
		}
		em.close();
		return ret;
	}
}
